package com.shop.zkmall.admin.controller;

import com.shop.zkmall.commons.utils.AppletPayUtil;
import io.springboot.captcha.GifCaptcha;
import io.springboot.captcha.utils.CaptchaJakartaUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/code")
@Tag(name = "验证码模块", description = "验证码模块")
public class CaptchaController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public static final String CAPTCHA_PREFIX = "captcha:admin:";

    //TODO 改造
    @GetMapping( "/captcha")
    @Operation(summary = "验证码总结")
    public void captcha(HttpServletRequest request, HttpServletResponse response){
        try {
            // 创建GifCaptcha对象
            GifCaptcha gifCaptcha = new GifCaptcha(130, 48, 4);
            // 输出验证码图片
            /*Captcha captcha = new Captcha();*/
            CaptchaJakartaUtil.out(gifCaptcha, request, response);
            //CaptchaUtil.out(gifCaptcha, request, response);
            // 获取验证码文本
            String verCode = gifCaptcha.text().toLowerCase();
            // 将验证码文本保存到session中
            //request.getSession().setAttribute("CAPTCHA", verCode);

            String ip = AppletPayUtil.getClientIp(request);
            System.out.println("ip:" + ip);
            redisTemplate.opsForValue().set(CAPTCHA_PREFIX + ip, verCode);

            // 打印session ID
            System.out.println(request.getSession().getId());
        } catch (Exception e) {
            log.error("getCaptcha error: " + e.getMessage(), e);
        }
    }
}
